import { _decorator, Component, instantiate, Layout, Node, Prefab, Size, UITransform, Vec2, Vec3 } from 'cc';
import { GameTools } from '../../../Utils/GameTools';
import { PathData } from '../../../Runtime/GameData';
import { eventMgr } from '../../../Runtime/EventManager';
import { GameEvent } from '../../../Runtime/GameEvent';
import { BagGrilditem } from '../Grild/BagGrilditem';
import { WeapItem } from '../Weap/WeapItem';
const { ccclass, property } = _decorator;

@ccclass('GrildManager')
export class GrildManager extends Component {
    private static instance: GrildManager;
    public static get Instance(): GrildManager {
        if (!GrildManager.instance) {
            GrildManager.instance = new GrildManager();
        }
        return GrildManager.instance;
    }
    //父节点
    private m_parentNode: Node = null;
    //预制体资源
    private pf_GrildItem: Prefab = null;
    // 格子总行列
    _bagGrid_row: number = 7;//列
    _bagGrid_col: number = 6;//行

    /**每一个小格子数据 */
    _gridwidth: number = 99;
    _gridheight: number = 99;
    _gridspace: number = 15;

    /**管理map数据 */
    _gridMapArr: string[][] = [];

    /**武器位置索引weapkey */
    private _weapOnGridMap: Map<string, WeapItem> = new Map<string, WeapItem>();
    public curWeapOnGridArr: number[] = [];
    get gridMapArr() {
        return this._gridMapArr;
    }
    set gridMapArr(value: string[][]) {
        this._gridMapArr = value;
    }

    get GridData() {
        return { width: this._gridwidth, height: this._gridheight, space: this._gridspace }
    }

    max_grid = this._bagGrid_row * this._bagGrid_col;
    private _gridEditMode: boolean = false;//是否为格子编辑模式

    get gridEditMode() {
        return this._gridEditMode;
    }

    set gridEditMode(value: boolean) {
        this._gridEditMode = value;
    }
    get GrildMaxSize() {
        return { row: this._bagGrid_row, col: this._bagGrid_col };
    }
    set GrildMaxSize(size: { row: number, col: number }) {
        this._bagGrid_row = size.row;
        this._bagGrid_col = size.col;
    }

    /**获取sizeMap数组坐标的值 */
    getPosBySizeMap(sizeMapStr: string): Vec2 {
        const [x, y] = sizeMapStr.match(/\(([^)]+)\)/)[1].split(" ");
        // 将坐标值转换为数字
        const xValue = parseInt(x, 10);
        const yValue = parseInt(y, 10);
        // 创建一个 Vec2 对象
        return new Vec2(xValue, yValue);
    }
    public async init() {
        eventMgr.on(GameEvent.PLACE_GRID_START, this.initAllGridList, this)
        await this.initGrildData()
    }
    protected onDisable(): void {
        eventMgr.off(GameEvent.PLACE_GRID_START, this.initAllGridList)
    }
    //读取数据
    public async initGrildData() {

        await GameTools.loadResAsync(PathData.pf_GrildItem, Prefab).then((res: Prefab) => {
            this.pf_GrildItem = res;
        })
    }
    /* 初始所有的背景格子 */
    initAllGridList(nodeParent: Node) {
        for (let x = 0; x < this.GrildMaxSize.row; x++) {
            for (let y = 0; y < this.GrildMaxSize.col; y++) {
                // 创建物品节点并添加到容器中
                const node: Node = instantiate(this.pf_GrildItem)
                node.parent = nodeParent
                const com: BagGrilditem = node.getComponent(BagGrilditem)
                com.create(x, y, `item_${x}_${y}`);

                console.log(`item_${x}_${y}`, node.getPosition())
                if (!this.gridMapArr[x]) {
                    this.gridMapArr[x] = []
                }

                this.gridMapArr[x][y] = '0';
            }
        }
        this.m_parentNode = nodeParent;
        this.initGridStatus();
        this.initGridSize();
    }


    /* 初始化格子状态 */
    initGridStatus() {
        let items = this.m_parentNode.children;
        for (let j = 0; j < items.length; j++) {
            const element = items[j];
            element.getComponent(BagGrilditem).setDeafult();
        }
    }
    /* 初始格子尺寸 */
    initGridSize() {
        let size = GrildManager.Instance.getGridSizeByRowCol(this._bagGrid_row, this._bagGrid_col);
        this.m_parentNode.getComponent(UITransform).setContentSize(size);
    }

    getIndexByPos(posx: number, posy: number): number {
        let items = this.m_parentNode.children;
        for (let j = 0; j < items.length; j++) {
            let position = items[j].getPosition();
            if (this.containsPosition(posx, position.x) && this.containsPosition(posy, position.y)) {
                return j;
            }
        }
        return -1;
    }

    containsPosition(child: number, parent: number) {
        //child数值大小在parent正负10的范围内
        return Math.abs(child - parent) <= 15;
    }

    /**根据行列获取格子坐标 */
    getGridPosByColRow(col: number, row: number): Vec3 {
        let index = col * this.GrildMaxSize.col + row;
        let items = this.m_parentNode.children;
        return items[index].getPosition();
    }
    /**
     * 通过行列数量获取尺寸
     */
    getGridSizeByRowCol(rowLen: number, colLen: number) {
        let size = new Size();
        let width = this.GridData.width;
        let height = this.GridData.height;
        let space = this.GridData.space;
        let w = rowLen * width + (rowLen - 1) * space;
        let h = colLen * height + (colLen - 1) * space;
        size.width = w;
        size.height = h;
        return size;
    }
    /**
 * 通过位置组获取位置中点坐标
 */
    getItemPosByTiledObj(gridObjArr: Array<number>) {
        const children = this.m_parentNode.children;
        const startcolrow = children[gridObjArr[0]].getComponent(BagGrilditem).gridObj;
        const endcolrow = children[gridObjArr[gridObjArr.length - 1]].getComponent(BagGrilditem).gridObj;
        let startPos = this.getGridPosByColRow(startcolrow.col, startcolrow.row);
        let endPos = this.getGridPosByColRow(endcolrow.col, endcolrow.row);
        let pos = new Vec3(0, 0, 0);
        pos.x = (startPos.x + endPos.x) / 2;
        pos.y = (startPos.y + endPos.y) / 2;
        return pos;
    }
    /* 检测武器id是否相同 */
    checkSameWeapoIdByKey(weaponKey: string, wid: string) {
        if (this._weapOnGridMap.has(weaponKey)) {
            let weaponObj = this._weapOnGridMap.get(weaponKey);
            if (wid == weaponObj.m_weapItemData.key) {
                return true;
            }
        }
        return false;
    }
    /**通过weapkey获取在格子内的武器 */
    getWeapItemByWeapKey(weaponKey: string) {
        if (this._weapOnGridMap.has(weaponKey)) {
            return this._weapOnGridMap.get(weaponKey);
        } else {
            return null;
        }
    }
    /**放置weapkey在格子内 */
    setWeapItemByWeapKey(weaponObj: WeapItem) {
        let weaponKey = weaponObj.m_weapItemData.weapKey;
        this._weapOnGridMap.set(weaponKey, weaponObj);
    }
    /**移除weapkey在格子内 */
    removeWeapItemByWeapKey(weaponKey: string) {
        if (this._weapOnGridMap.has(weaponKey)) {
            this._weapOnGridMap.delete(weaponKey);
        }
    }

}
export const GridMgr = GrildManager.Instance;


